package com.gac.basedownload.inner;

import android.util.Log;

import com.gac.basedownload.model.DownloadRecord;
import com.gac.basedownload.model.FileRecord;
import com.litesuits.orm.db.assit.QueryBuilder;

import java.util.List;

public class DBUtils {


    public static List<DownloadRecord> getDownloadRecordList(String fileId){
       List<DownloadRecord> list =  LiteOrmHelper.getInstance().query(
               new QueryBuilder(DownloadRecord.class).whereEquals("fileId",fileId));
       return list;
    }

    //获取已经下载的长度
    public static long getDownloadedLen(String fileId){
        List<DownloadRecord> list = null;
        list = getDownloadRecordList(fileId);

        long total = 0;
        if(list != null){
            for(int i = 0; i < list.size(); i++){
                total+= list.get(i).getDownloadLen();
            }
        }
        return total;
    }

    public static void removeDownloadRecord(DownloadRecord record){
        LiteOrmHelper.getInstance().delete(record);
    }

    public static void insertDownloadRecord(DownloadRecord record){
        LiteOrmHelper.getInstance().insert(record);
    }


    public static void updateDownloadRecord(DownloadRecord record){
        LiteOrmHelper.getInstance().update(record);
    }


    public static long getAllDownloadCount(){
        return LiteOrmHelper.getInstance().queryCount(DownloadRecord.class);
    }


    public static FileRecord getFileRecord(String fileId){
        return LiteOrmHelper.getInstance().queryById(fileId,FileRecord.class);
    }


    public static FileRecord getFileRecordByUrl(String url){
        List<FileRecord> list =  LiteOrmHelper.getInstance().query(
                new QueryBuilder(FileRecord.class).whereEquals("url",url));
        Log.e("gacmy","list File size:"+list.size());

        if(list != null && list.size() > 0){
            return list.get(0);
        }
        return null;
    }

    public static void removeFileRecord(FileRecord record){
        LiteOrmHelper.getInstance().delete(record);
        List<DownloadRecord> list = getDownloadRecordList(record.getFileId());
        if(list == null){
            return;
        }
        for(int i = 0; i < list.size(); i++){
            removeDownloadRecord(list.get(i));
        }

    }




    public static void insertFileRecord(FileRecord record){
        LiteOrmHelper.getInstance().insert(record);
    }


    public static void updateFileRecord(FileRecord record){
        LiteOrmHelper.getInstance().update(record);
    }

}
